import React, {Component} from 'react';
import Header from '../common/header';
import * as URLconstant from '../constant/URLconstant'
import Util from '../common/util'
import Toast from '../common/ToastUtil'
import DatePicker from 'react-native-modal-datetime-picker'
import {
    View,
    Text,
    ScrollView,
    Image,
    TouchableOpacity,
    TextInput,
    StyleSheet
} from 'react-native';

export default class selectLogistics extends Component {
    // 构造
    constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            logisList: null,
            shipping_id: null,
            showSecond: false,
            isNow: 1,
            selectTime: '',
            isShowDateTimePicker: false,
            selectItem: null,
            inTime: false
        };
        this.getLogisticsSuc = this.getLogisticsSuc.bind(this)
        this.errorCallback = this.errorCallback.bind(this)
    }

    componentDidMount() {
        this.getLogistics()
    }

    getLogistics() {
        let params = this.props.route.params
        let url = URLconstant.GET_LOGISTICS
        let datakey = []
        datakey['user_id'] = params.user_id
        Util.get(url, datakey, this.getLogisticsSuc, this.errorCallback)
    }

    getLogisticsSuc(datas) {
        if (datas.status == 1) {
            this.setState({
                logisList: datas.data
            })
        }
    }

    errorCallback(err) {

    }

    selectLogi(item) {
        let self_delivery = item.self_delivery
        let showSecond = false
        let inTime = true
        if (self_delivery == 1) {
            showSecond = true
            if (this.state.isNow == 1) {
                inTime = this.isInTime(item.start_time, item.end_time)
            }
        }
        this.setState({
            shipping_id: item.shipping_id,
            selectItem: item,
            showSecond: showSecond,
            inTime: inTime
        })
    }


    isInTime(start_time, end_time) {
        let selectTime = this.state.selectTime
        let date
        if (selectTime == '') {
            date = new Date()
        } else {
            date = selectTime
        }
        let timestamp = Date.parse(date) / 1000
        let Y = date.getFullYear() + '/';
        let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
        let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
        let start_timestamp = Date.parse(new Date(Y + M + D + start_time + ":00")) / 1000
        let end_timestamp = Date.parse(new Date(Y + M + D + end_time + ":00")) / 1000
        let inTime = false
        if (timestamp >= start_timestamp && timestamp <= end_timestamp) {
            inTime = true
        }
        return inTime
    }

    //选择配送时间
    selectLogiTime(isNow) {
        let selectItem = this.state.selectItem
        let inTime = true
        if (isNow == 1) {
            inTime = this.isInTime(selectItem.start_time, selectItem.end_time)
        }
        this.setState({
            isNow: isNow,
            inTime: inTime
        })
    }

    backDate() {
        let selectTime = this.state.selectTime
        let date
        if (selectTime == '') {
            date = new Date()
        } else {
            date = selectTime
        }
        let timeTxt = this.backTimeTxt(date)
        return timeTxt
    }


    backTimeTxt(date) {
        let year = date.getFullYear() + '/';
        let month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
        let day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
        let hours = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ":"
        let minutes = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ":"
        let seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
        let timeTxt = year + month + day + hours + minutes + seconds
        return timeTxt
    }


    showLogisList() {
        let logisList = this.state.logisList
        return (
            <View>
                <View style={[styles.padding_view]}>
                    <View style={styles.rows_view}>
                        <Text style={{fontSize: 16, color: "#000"}}>选择配送方式</Text>
                    </View>
                    <ScrollView horizontal={true}>
                        {
                            logisList.map((item, index) => {
                                return (
                                    <View style={{alignItems: 'center', justifyContent: 'center'}} key={index}>
                                        <TouchableOpacity onPress={() => this.selectLogi(item)} key={index}
                                                          style={item.shipping_id == this.state.shipping_id ? styles.select_logi_item : styles.logi_item}>
                                            <Text style={item.shipping_id == this.state.shipping_id ? {
                                                fontSize: 16,
                                                color: "#fff"
                                            } : {fontSize: 16, color: "#333"}}>{item.shipping_name}</Text>
                                            {
                                                item.shipping_promise == 0 || item.description == '' || item.description == undefined ?
                                                    null :
                                                    <Text numberOfLines={1}
                                                          style={item.shipping_id == this.state.shipping_id ? {
                                                              fontSize: 12,
                                                              color: "#fff",
                                                              marginTop: 5
                                                          } : {
                                                              fontSize: 12,
                                                              color: "#696969",
                                                              marginTop: 5
                                                          }}>{item.shipping_promise}小时送达</Text>
                                            }
                                        </TouchableOpacity>
                                    </View>
                                )
                            })
                        }
                    </ScrollView>
                </View>
                {
                    this.state.showSecond ?
                        <View style={styles.select_logi_time}>
                            <TouchableOpacity onPress={() => this.selectLogiTime(1)}
                                              style={this.state.isNow == 1 ? styles.selected_time_item : styles.select_time_item}>
                                <Text style={this.state.isNow == 1 ? {fontSize: 14, color: "#fff"} : {
                                    fontSize: 14,
                                    color: "#333"
                                }}>马上送</Text>
                            </TouchableOpacity>
                            <TouchableOpacity onPress={() => this.selectLogiTime(2)}
                                              style={this.state.isNow == 2 ? styles.selected_time_item : styles.select_time_item}>
                                <Text style={this.state.isNow == 2 ? {fontSize: 14, color: "#fff"} : {
                                    fontSize: 14,
                                    color: "#333"
                                }}>预约时间</Text>
                            </TouchableOpacity>
                        </View> :
                        null
                }
                {
                    this.state.showSecond == true && this.state.isNow == 2 ?
                        <TouchableOpacity onPress={() => this.setState({isShowDateTimePicker: true})}
                                          style={styles.time_select_view}>
                            <Text style={{fontSize: 14, color: "#333"}}>预约送货时间：</Text>
                            <Text style={{fontSize: 14, color: "#333"}}>{this.backDate()}</Text>
                        </TouchableOpacity>
                        :
                        null
                }
                {
                    this.state.selectItem != null && this.state.selectItem.description ?
                        <View style={[styles.time_select_view]}>
                            <Text style={{fontSize: 14, color: "#333"}}>配送描述</Text>
                            <Text style={{fontSize: 14, color: "#333"}}>{this.state.selectItem.description}</Text>
                        </View> : null
                }
                {
                    this.state.shipping_id == null ? null :
                        <View style={{paddingVertical: 10, alignItems: 'center'}}>
                            {
                                this.state.isNow == 1 ?
                                    <Text style={{
                                        fontSize: 12,
                                        color: "#969696"
                                    }}>{this.state.inTime ? "支付后，将马上为您配送" : "不好意思，当前不在配送时间内，请选择配送预约"}</Text>
                                    :
                                    <Text style={{fontSize: 12, color: "#969696"}}>支付后，将在您预约时间内为您配送</Text>
                            }
                        </View>
                }
            </View>
        )
    }

    _handleDatePicked = (date) => {
        LOG('date===' + date)
        this.setState({
            selectTime: date
        })
        this._hideDateTimePicker()
    }

    submitLogi() {
        let selectItem = this.state.selectItem
        if (selectItem == undefined) {
            Toast.show('请选择配送方式')
        } else {
            if (selectItem.self_delivery == 1) {
                let isNow = this.state.isNow
                if (isNow == 1) {
                    if (this.isInTime(selectItem.start_time, selectItem.end_time) == false) {
                        Toast.show('不在配送时间' + selectItem.start_time + '-' + selectItem.end_time + '内')
                    }
                    selectItem.delivery_type = 2
                } else {
                    selectItem.delivery_type = 1
                    selectItem.ship_time = Date.parse(this.state.selectTime) / 1000
                }
            }
            let params = this.props.route.params
            if (params.callback) {
                params.callback(selectItem);
            }
            this.props.navigation.pop()
        }
    }


    _hideDateTimePicker = () => this.setState({isShowDateTimePicker: false})

    render() {
        return (
            <View style={{flex: 1, backgroundColor: "#f0f0f0"}}>
                <Header navigation={this.props.navigation} title={"配送方式"}/>
                {
                    this.state.logisList == null ?
                        <View style={{flex: 1}}>
                            {Util.loading()}
                        </View>
                        :
                        <View style={{flex: 1}}>
                            <View style={{flex: 1}}>
                                {this.showLogisList()}
                            </View>
                            <View style={{padding: 20}}>
                                {
                                    this.state.inTime == true ?
                                        <TouchableOpacity onPress={() => this.submitLogi()} style={styles.confirm_btn}>
                                            <Text style={{fontSize: 16, color: "#fff"}}>确定</Text>
                                        </TouchableOpacity> :
                                        <View style={styles.confirm_btn2}>
                                            <Text style={{fontSize: 16, color: "#fff"}}>确定</Text>
                                        </View>
                                }
                            </View>
                            <DatePicker
                                visible={this.state.isShowDateTimePicker}
                                onConfirm={this._handleDatePicked}
                                onCancel={this._hideDateTimePicker}
                                titleIOS="请选择配送时间"
                                cancelTextIOS='取消'
                                confirmTextIOS='确定'
                                date={new Date()}
                                mode={'datetime'}
                            />
                        </View>
                }
            </View>
        )
    }
}
var styles = StyleSheet.create({
    padding_view: {
        paddingHorizontal: 10,
        paddingBottom: 10
    },
    rows_view: {
        flexDirection: "row",
        alignItems: 'center',
        paddingVertical: 10
    },
    logi_item: {
        width: 120,
        height: 60,
        borderRadius: 7,
        borderWidth: 1,
        borderColor: "#696969",
        alignItems: "center",
        justifyContent: 'center',
        marginRight: 10,
        backgroundColor: "#fff"
    },
    select_logi_item: {
        width: 120,
        height: 60,
        borderRadius: 7,
        borderWidth: 1,
        borderColor: "#ee1f12",
        alignItems: "center",
        justifyContent: 'center',
        marginRight: 10,
        backgroundColor: "#ee1f12"
    },
    confirm_btn: {
        height: 40,
        alignItems: "center",
        justifyContent: 'center',
        backgroundColor: "#ee1f12",
        borderRadius: 20
    },
    confirm_btn2: {
        height: 40,
        alignItems: "center",
        justifyContent: 'center',
        backgroundColor: "#969696",
        borderRadius: 20
    },
    select_logi_time: {
        flexDirection: "row",
        alignItems: 'center',
        padding: 10,
        backgroundColor: "#fbfbfd",
        borderTopWidth: 1,
        borderTopColor: "#ccc",
    },
    select_time_item: {
        paddingHorizontal: 15,
        height: 30,
        backgroundColor: "#fff",
        borderRadius: 15,
        borderWidth: 1,
        borderColor: "#696969",
        alignItems: "center",
        justifyContent: 'center',
        marginRight: 10
    },
    selected_time_item: {
        paddingHorizontal: 15,
        height: 30,
        borderRadius: 15,
        borderWidth: 1,
        borderColor: "#ee1f12",
        alignItems: "center",
        justifyContent: 'center',
        marginRight: 10,
        backgroundColor: "#ee1f12"
    },
    time_select_view: {
        padding: 10,
        backgroundColor: "#fbfbfd",
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        height: 50,
        borderTopWidth: 1,
        borderTopColor: "#ccc",
    }
})